import requests
import re
import time
import random

def get_id_from_url(url) -> str:
    """pwd_id"""
    pattern = r"/s/(\w+)"
    match = re.search(pattern, url)
    if match:
        return match.group(1)
    return ""


def generate_timestamp(length):
    timestamps = str(time.time() * 1000)
    return int(timestamps[0:length])


class Quark:
    ad_pwd_id = "0df525db2bd0"

    def __init__(self, cookie: str) -> None:
        self.headers = {
            'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            'accept': 'application/json, text/plain, */*',
            'content-type': 'application/json',
            'sec-ch-ua-mobile': '?0',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'sec-ch-ua-platform': '"Windows"',
            'origin': 'https://pan.quark.cn',
            'sec-fetch-site': 'same-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://pan.quark.cn/',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cookie': cookie}

    def store(self, url: str):
        pwd_id = get_id_from_url(url)
        stoken = self.get_stoken(pwd_id)
        detail = self.detail(pwd_id, stoken)
        first_id, share_fid_token, file_type = detail.get("fid"), detail.get("share_fid_token"), detail.get(
            "file_type")
        self.save_task_id(pwd_id, stoken, first_id, share_fid_token,"a1ef45c43d7a4cbf8fcb6403604da616")

    def get_stoken(self, pwd_id: str):
        url = f"https://drive-pc.quark.cn/1/clouddrive/share/sharepage/token?pr=ucpro&fr=pc&uc_param_str=&__dt=405&__t={generate_timestamp(13)}"
        payload = {"pwd_id": pwd_id, "passcode": ""}
        headers = self.headers
        response = requests.post(url, json=payload, headers=headers).json()
        if response.get("data"):
            return response["data"]["stoken"]
        else:
            return ""

    def detail(self, pwd_id, stoken):
        url = f"https://drive-pc.quark.cn/1/clouddrive/share/sharepage/detail"
        headers = self.headers
        params = {
            "pwd_id": pwd_id,
            "stoken": stoken,
            "pdir_fid": 0,
            "_page": 1,
            "_size": "50",
        }
        response = requests.request("GET", url=url, headers=headers, params=params)
        id_list = response.json().get("data").get("list")[0]
        if id_list:
            data = {
                "title": id_list.get("file_name"),
                "file_type": id_list.get("file_type"),
                "fid": id_list.get("fid"),
                "pdir_fid": id_list.get("pdir_fid"),
                "share_fid_token": id_list.get("share_fid_token")
            }
            return data

    def save_task_id(self, pwd_id, stoken, first_id, share_fid_token, to_pdir_fid=0):
        url = "https://drive.quark.cn/1/clouddrive/share/sharepage/save"
        params = {
            "pr": "ucpro",
            "fr": "pc",
            "uc_param_str": "",
            "__dt": int(random.uniform(1, 5) * 60 * 1000),
            "__t": generate_timestamp(13),
        }
        data = {"fid_list": [first_id],
                "fid_token_list": [share_fid_token],
                "to_pdir_fid": to_pdir_fid, "pwd_id": pwd_id,
                "stoken": stoken, "pdir_fid": "0", "scene": "link"}
        response = requests.request("POST", url, json=data, headers=self.headers, params=params)
        task_id = response.json().get('data').get('task_id')
        return task_id




if __name__ == '__main__':
    cookie = "_UP_A4A_11_=wb965190cf0349d9ad8fc9e62ee49ba2; b-user-id=c8a6434b-c4a8-6973-a9c7-870a66de599b; __wpkreporterwid_=fc4e2701-d003-4a50-31e2-d86f6f55d06a; __itrace_wid=ceaddecc-1fed-4871-b0ef-8f20a7e0d95f; __sdid=AATstE+XEtZarQYwY9A7ZGZbQIkEhnqUnwW9d+SH4Oi9RA8t1FJTgX7wvGM7mhDTP0w=; _UP_D_=pc; isg=BPHxp4l3Mn8Nzp9SQaOyI3vxAH2L3mVQl9KHDNME77jX-hJMGy9CIDwZGI6cMv2I; _qk_bx_um_v1=eyJ1ZCI6IlQyZ0FVZ2J1TFVuSFdJWmplOUgwSURyc0NBUU95M0lYZWJSdTVrV1lKdzdMNWU3WDIzSWZsS2NabWVXNC1oSFlxM3M9IiwiZXAiOjE3NDU0MTA5NzczOTl9; _ON_EXT_DVIDN=eCy#AAOQUrsWMcjTV3VxsWI6zxTyxTK4wZT51ojZkbNd4vXYgbzE4a5zXHh6a/R5p1VgEmk=; _qk_bx_ck_v1=eyJkZXZpY2VJZCI6ImVDeSNBQU9RVXJzV01jalRWM1Z4c1dJNnp4VHl4VEs0d1pUNTFvalprYk5kNHZYWWdiekU0YTV6WEhoNmEvUjVwMVZnRW1rPSIsImRldmljZUZpbmdlcnByaW50IjoiNDMwMWU0ZWRlNWJkYTRkYzBmYWUyM2Q0OTFjODg2MzAifQ==; ctoken=YEV9v2Su4c0SufSFXdtkubt2; grey-id=cc880152-b442-7794-fa86-23a4948d36a2; grey-id.sig=dZZe7Wt4cuZ7bP40NpLLYW4eaasu5HU0zsDj-aMHjV4; isQuark=true; isQuark.sig=hUgqObykqFom5Y09bll94T1sS9abT1X-4Df_lzgl8nM; _UP_F7E_8D_=B6GHd90IIys%2B9ca5PC62wksem8D%2BGJzLUdRO7YsGUI%2BibipNZ4wWoKA3nkVDHeUjK77U6xYgqMbXDik4ZZxmO%2B6jibaMeh%2F15GPrrCl5M87ivs0EP%2FjAQTQimMgEdat62Byd22%2BZGM7tkT7YXh13fkMTbjI7TrIF4dnjse%2B2%2BrbAu1yFnsYfYpkeu7XFGZeS6sexB%2BSD9CYjn7qLCZqy1wYX8nQI3NkEzFS6A%2Fy114eJD2f4HkNgN92V0G8Hu2tUwfciFhKhTDYBhMXt42IX5T0OABK9vhV%2B%2Biyn4QWXu%2BfLRM2xxJkw6XwNx%2BLGXCRhOnBIJjjnrh8cYD1zLEqy17ekFFQtJNHwljufc%2FrNRhob6h8YLOwy6Xc0ZjrCXqUEhJgnZxINLXTQeOqFvcVxa4vBJJJ28YPE; _UP_30C_6A_=st9c8620135zmdcsqx894dsf0awzdn34; _UP_TS_=sg18f855892013c281b07d347cf7a99a855; _UP_E37_B7_=sg18f855892013c281b07d347cf7a99a855; _UP_TG_=st9c8620135zmdcsqx894dsf0awzdn34; _UP_335_2B_=1; __pus=4e4b0279d5ff39fc08ae3715b569b1aaAATtlHiK8+7g3LG1acVNrbWDZdwJsm5E//nN0DGzCW0mZtqIgGUI9nhFnsi5b6TxDq+rEUBOtmkLSBiXvT8hpU3A; __kp=aab6a460-200f-11f0-a92e-9b0e61eae590; __kps=AASRlW8euqWX/Oo/4iKh+vpI; __ktd=bvTTTVSdItGku/UQR3qy3w==; __uid=AASRlW8euqWX/Oo/4iKh+vpI; web-grey-id=0d675a8c-0ed9-0ca2-4ef6-e8874d1726bf; web-grey-id.sig=8dshKbAUT-yEqK9MCp_VbleBTB7oZ41ryigCOdUlV4U; tfstk=gx3EpItixeLec6ueE54P0BH7UyaLzyvjx4w7ZbcuOJ23OyGobbG297MIZ8ozIYddRyvdr8cxBkwnFy6yzAz32Dw7d8zrwxR6hETj9XU8qK9Xl6BvFqzYtwjhFPYgOzP3w4EH5XU8rd9KlYrI9vU30zg3rCzgaW2uraDuIf2Tw7X3ZwAZsReG-723tGfgM76hKY4k_f2TZz2oMgDKetN0xQZEzibVHCZ3nX2NrZ5YLkvKOg_VuVPUYkh3QkrE7WrUnlM-HWunCb0IJlKAczhs0YooIF7EUXmmEJgMnaySD7lugrYAgR0EaVrKf9j3gyyUm2qGGNGgqcuaR2vRDfGaKozsfhpQVykED-EHXdHr_JMo8lXeC8ij12qZnd_ZeuonL54c4zB8squjyDWlqkVT_-Ow_XnJcmpRstyA2gEgm5yX9ujR2kVT_-Ow_gI8vZVahBEl.; __puus=3ea17ce60297c904018437f71312c0deAAQlkPodNjMfEc7JClWdDGG54j5lsimKU+buqC4+Q4R0SI+27KQUw3eb4/whs46ck0wHqX70Q9O8esnjGkI00G0MgTHolbDncFezRbMrjHgw7tUbrXQ6Lb8ToqyJxl264+XTtufcjCfA/1XO0RR/D7ES6XWa6ScZXVFB23RwsOXql59oMtUziAJgbCYQHaZkiGat+Zh8HSDikmf7ZvRN3OI5"
    quark = Quark(cookie)
    quark.store('https://pan.quark.cn/s/adb53a54c608')

